import { getAwsConfig } from '@/api/common.js'
import Compressor from 'compressorjs'
const REGION = 'us-east-1'

import AWS from 'aws-sdk'

// AWS 前端开发文档 https://docs.aws.amazon.com/zh_cn/sdk-for-javascript/v2/developer-guide/s3-example-photo-album.html
/**
 * @param {file||Blob} file 文件对象
 * @param profile  用戶信息
 */

export function upFile(file, menu, fileName, cb, path) {
  return new Promise((resolve, reject) => {
    compressorFun(file).then(res => {
      const _compressorfile = res
      getFileInfo(_compressorfile).then(data => {
        getAwsConfig().then((res) => {
          const { bucket, domain, identityPoolId } = res.data
          console.log(data, '-=getFileInfo---')
          const Key = path || `${process.env.NODE_ENV === 'production' ? '' : 'dev/'}${menu}/${fileName}_${new Date().getTime()}.${data.suffix}`
          const uploadParams = {
            Bucket: bucket,
            Key,
            Body: _compressorfile
          }

          AWS.config.update({
            region: REGION,
            credentials: new AWS.CognitoIdentityCredentials({
              IdentityPoolId: identityPoolId
            })
          })

          const upload = new AWS.S3.ManagedUpload({
            params: uploadParams
          })

          const promise = upload.promise()
          promise.then(
            (data) => {
              resolve({
                filePath: `${domain}/${uploadParams.Key}`,
                giftfilePath: `${domain}${uploadParams.Key}`,
                path: `/${uploadParams.Key}`,
                giftpath: `${uploadParams.Key}`,
                msg: 'success'
              })
            },
            (err) => {
              return reject(err)
            }
          )
        })
      })
        .catch(e => {
          reject({
            msg: 'server error',
            error: e
          })
        })
    }).catch(e => {
      reject({
        msg: 'server error',
        error: e
      })
    })
  })
}

export function upFileWithkkImgBucket(file, menu, fileName, cb, path) {
  return new Promise((resolve, reject) => {
    compressorFun(file).then(res => {
      const _compressorfile = res
      getFileInfo(_compressorfile).then(data => {
        getAwsConfig().then((res) => {
          const { kkImgBucket, identityPoolId, kkImgDomain } = res.data
          console.log(data, '-=getFileInfo---')
          const Key = path || `${process.env.NODE_ENV === 'production' ? '' : 'dev/'}${menu}/${fileName}_${new Date().getTime()}.${data.suffix}`
          const uploadParams = {
            Bucket: kkImgBucket,
            Key,
            Body: _compressorfile
          }

          AWS.config.update({
            region: REGION,
            credentials: new AWS.CognitoIdentityCredentials({
              IdentityPoolId: identityPoolId
            })
          })

          const upload = new AWS.S3.ManagedUpload({
            params: uploadParams
          })

          const promise = upload.promise()
          promise.then(
            (data) => {
              resolve({
                filePath: `${kkImgDomain}/${uploadParams.Key}`,
                path: `/${uploadParams.Key}`,
                msg: 'success'
              })
            },
            (err) => {
              return reject(err)
            }
          )
        })
      })
        .catch(e => {
          reject({
            msg: 'server error',
            error: e
          })
        })
    }).catch(e => {
      reject({
        msg: 'server error',
        error: e
      })
    })
  })
}

// 获取file信息
export function getFileInfo(fileObj) {
  if (fileObj.type && fileObj.type.match(/video/)) {
    // eslint-disable-next-line space-before-function-paren
    return new Promise(function (resolve, reject) {
      if (fileObj.type !== 'video/mp4') {
        reject('请上传正确的视频文件类型')
      }

      if (fileObj.size > 200 * 1024 * 1024) {
        reject('视频文件过大')
      }

      // 获取上传的视频的宽高
      const videoUrl = URL.createObjectURL(fileObj)
      const videoObj = document.createElement('video')

      // eslint-disable-next-line space-before-function-paren
      videoObj.onloadedmetadata = function (evt) {
        URL.revokeObjectURL(videoUrl)
        resolve({
          w: videoObj.videoWidth,
          h: videoObj.videoHeight,
          duration: videoObj.duration,
          suffix: fileObj.type.substring(fileObj.type.indexOf('/') + 1),
          mimeType: 1
        })
      }

      videoObj.src = videoUrl
      videoObj.load()
    })
  } else if (fileObj.type && fileObj.type.match(/image/)) {
    // eslint-disable-next-line space-before-function-paren
    return new Promise(function (resolve, reject) {
      // 获取上传的图片的宽高
      const reader = new FileReader()
      reader.readAsDataURL(fileObj)
      // eslint-disable-next-line space-before-function-paren
      reader.onload = function (evt) {
        const replaceSrc = evt.target.result

        const imageObj = new Image()
        imageObj.src = replaceSrc
        // eslint-disable-next-line space-before-function-paren
        imageObj.onload = function () {
          resolve({
            w: imageObj.width,
            h: imageObj.height,
            suffix: fileObj.type.substring(fileObj.type.indexOf('/') + 1),
            mimeType: 2
          })
        }
      }
    })
  } else if (fileObj.type && (fileObj.type.match(/zip/) || fileObj.type.match(/mp4/))) {
    // eslint-disable-next-line space-before-function-paren
    return new Promise(function (resolve, reject) {
      resolve({
        suffix: fileObj.type.substring(fileObj.type.indexOf('/') + 1),
        mimeType: 3
      })
    })
  } else {
    // eslint-disable-next-line new-cap
    return new Promise.reject('不支持该文件格式上传！')
  }
}

// 压缩图片方法
function compressorFun(file, defaultQuality = 0.6) {
  console.log('压缩前: ', (file.size / 1024 / 1024).toFixed(1), 'M')// 控制台打印图片大小
  const filesize = (file.size / 1024 / 1024).toFixed(1)
  let quality = defaultQuality
  if (filesize < 5) {
    quality = 1
  } else if (filesize < 8) {
    quality = 0.6
  } else if (filesize < 15) {
    quality = 0.4
  } else {
    return new Promise((resolve, reject) => {
      reject({
        msg: 'The image should not exceed 15M'
      })
    })
  }
  console.log('压缩比例: ', quality)

  return new Promise((resolve) => {
    new Compressor(file, {
      quality: quality,
      success(result) {
        console.log('压缩后: ', (result.size / 1024 / 1024).toFixed(1), 'M')
        resolve(result)
      },
      error() {
        resolve(file)
      }
    })
  })
}
